package cn.edu.ldh.toolapp.slice;

import cn.edu.ldh.toolapp.ResourceTable;
import cn.edu.ldh.toolapp.entity.NoteItem;
import cn.edu.ldh.toolapp.entity.NoteItemRes;
import cn.edu.ldh.toolapp.stores.NoteStore;
import cn.edu.ldh.toolapp.util.ToastUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddNoteAbilitySlice extends AbilitySlice {

    TextField tfTitle;
    TextField tfContent;
    Button btnSub;
    Button btnBack;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_addnote);
        this.startInit();
    }

    //初始化组件
    private void startInit() {
        tfTitle = (TextField) findComponentById(ResourceTable.Id_tf_note_title);
        tfContent = (TextField) findComponentById(ResourceTable.Id_tf_note_content);
        //初始化清空内容
        tfTitle.setText("");
        tfContent.setText("");
        btnSub = (Button) findComponentById(ResourceTable.Id_btn_note_sub);
        btnBack = (Button) findComponentById(ResourceTable.Id_btn_note_back);
        btnSub.setClickedListener(this::subNote);
        btnBack.setClickedListener(this::backNote);
    }

    private void backNote(Component component) {
        terminate();
    }

    //增加日记
    private void subNote(Component component) {
        String title = tfTitle.getText();
        String content = tfContent.getText();
        if(title.equals("")) {
            new ToastDialog(getContext()).setText("请输入标题")
                    .setAlignment(LayoutAlignment.CENTER).show();
            return;
        }
        if (content.equals("")) {
            new ToastDialog(getContext()).setText("请输入内容")
                    .setAlignment(LayoutAlignment.CENTER).show();
            return;
        }
        NoteItem noteItem = new NoteItem();
        noteItem.setNoteTitle(title);
        noteItem.setNoteContent(content);
        Date date = new Date();
        noteItem.setNoteDate(new SimpleDateFormat("yyyy-MM-dd").format(date));
        NoteItemRes noteItemRes = NoteStore.getInstance().insertNote(noteItem);
        if(noteItemRes.getCode() == 200) {
            ToastUtil.showToast(getContext(), noteItemRes.getMessage());
            present(new NoteAbilitySlice(), new Intent());
        } else {
            ToastUtil.showToast(getContext(), noteItemRes.getMessage());
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
